package com.atguigui.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * 滑动窗口的平均值
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by  wangjiaxin  on 2022/7/16 17:53
 */
public class POfferII041QIsx9U {
    public static void main(String[] args) {
        MovingAverage solution = new POfferII041QIsx9U().new MovingAverage(3);
        // TO TEST
    }

    class MovingAverage {

        private int windowSize;
        private List<Integer> list;

        public MovingAverage(int size) {
            windowSize = size;
            list = new ArrayList<>();
        }

        public double next(int val) {
            list.add(val);
            double ans = 0.0;
            if (list.size() > windowSize) {
                double sum = 0;
                for (int i = list.size() - 1; i > list.size() - 1 - windowSize; i--) {
                    sum += list.get(i);
                }
                ans = sum / windowSize;
            } else {
                double sum = 0;
                for (Integer integer : list) {
                    sum += integer;
                }
                ans = sum / list.size();
            }

            return ans;
        }
    }
}
